<template>
  <a-modal :open="open" width="60%" title="电子签名" centered :footer="null" destroy-on-close @cancel="onCancel">
    <BaseTitle title="员工信息" class="mt-4" />
    <div class="flex items-center flex-wrap border border-blue-500 rounded-lg px-4 py-2 bg-secondary">
      <LabelValue class="mt-2" label="员工编号" :width="240" :value="rowData.empId" />
      <LabelValue class="mt-2" label="员工名称" :width="240" :value="rowData.empName" />
      <LabelValue class="mt-2" label="性别" :width="240" :value="rowData.sex" />
      <LabelValue class="mt-2" label="手机号" :width="240" :value="rowData.phone" />
      <LabelValue class="mt-2" label="职称" :width="240" :value="rowData.title" />
      <LabelValue class="mt-2" label="部门" :width="240" :value="rowData.bmmc" />
      <LabelValue class="mt-2" label="科室" :width="240" :value="rowData.ksmc" />
    </div>
    <div>
      <BaseTitle title="签名区域" class="mt-4" />
      <div class="h-[450px] border my-4 border-[#ccc]">
        <img v-if="currentData.signImgUrl" :src="currentData.signImgUrl" alt="" class="max-h-[430px] max-w-full" />
        <VueSignaturePad v-else ref="signaturePadRef" :options="options" />
      </div>
      <footer class="flex items-center pt-4 pb-8 justify-between">
        <div class="flex">
          <a-button type="primary" @click="fileRef.click()">上传图片</a-button>
          <input ref="fileRef" type="file" accept="image/png" class="hidden" @change="onUploadImg" />
        </div>
        <div class="flex">
          <div class="flex ml-4 items-center" :class="{ disabled: !!currentData.signImgUrl }">
            <div class="penTxt">笔刷大小：</div>
            <div class="circleWrap" :class="{ active: activePen === 1 }" @click="onChoosePenSize(1)"><b class="b1"></b></div>
            <div class="circleWrap" :class="{ active: activePen === 2 }" @click="onChoosePenSize(2)"><b class="b2"></b></div>
            <div class="circleWrap" :class="{ active: activePen === 3 }" @click="onChoosePenSize(3)"><b class="b3"></b></div>
          </div>
          <a-button type="primary" :disabled="!!currentData.signImgUrl && !isSelf" ghost @click="onUndo">撤销</a-button>
          <a-button type="primary" :disabled="!!currentData.signImgUrl && !isSelf" ghost class="ml-6" @click="onClear">清屏</a-button>
          <a-button v-if="currentData.signImgUrl && !isSelf" type="primary" class="ml-6" @click="currentData.signImgUrl = ''">重签</a-button>
          <a-button v-else type="primary" class="ml-6" @click="onSave">保存</a-button>
        </div>
      </footer>
    </div>
  </a-modal>
</template>
<script setup>
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { VueSignaturePad } from 'vue-signature-pad'
import axios from 'axios'

const emit = defineEmits(['update:open', 'confirm', 'success'])
const currentData = ref({})
const isSelf = ref(false)
const fileRef = ref(null)
const signaturePadRef = ref(null)
const activePen = ref(1)
const options = ref({
  penColor: '#000',
  minWidth: 2, //控制画笔最小宽度
  maxWidth: 2 //控制画笔最大宽度
})
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => ({})
  }
})

const onSave = async () => {
  const res = await onUpload()
  if (res.code === 0) {
    const { code, msg } = await post('/operation/opex/doSaveEmpInfo', { ...currentData.value, signImgUrl: res.data.fileName })
    if (code !== 0) return message.error(msg || '保存失败')
    message.success('保存成功')
    emit('update:open', false)
    emit('success')
  }
}

const onClearSignUrl = async () => {
  const { code, msg } = await post('/operation/opex/doSaveEmpInfo', { ...currentData.value, signImgUrl: '' })
  if (code !== 0) return message.error(msg || '保存失败')
  message.success('保存成功')
  emit('update:open', false)
  emit('success')
}

const onUpload = async () => {
  let signatureFile = null
  if (isSelf.value) {
    signatureFile = base64toFile(currentData.value['signImgUrl'], currentData.value.empName + '签名.png')
  } else {
    const { isEmpty, data } = signaturePadRef.value.saveSignature()
    if (isEmpty) return onClearSignUrl()
    signatureFile = base64toFile(data, currentData.value.empName + '签名.png')
  }
  const formData = new FormData()
  formData.append('file', signatureFile)
  const { data: res } = await axios.post('/api/v1/common/util/doUploadFile', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
  return res
}

const onUploadImg = (e) => {
  const file = e.target.files[0]
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    isSelf.value = true
    currentData.value['signImgUrl'] = reader.result
  }
}
const onClear = () => {
  if (isSelf.value) {
    currentData.value['signImgUrl'] = ''
    isSelf.value = false
  } else {
    signaturePadRef.value.clearSignature()
  }
}
const onUndo = () => {
  if (isSelf.value) {
    currentData.value['signImgUrl'] = ''
    isSelf.value = false
  } else {
    signaturePadRef.value.undoSignature()
  }
}

const onChoosePenSize = (val) => {
  activePen.value = val
  options.value = {
    penColor: '#000',
    minWidth: val + 1, //控制画笔最小宽度
    maxWidth: val + 1 //控制画笔最大宽度
  }
}

const base64toFile = (base64Data, filename) => {
  const arr = base64Data.split(',')
  const mime = arr[0].match(/:(.*?);/)[1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)

  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, { type: mime })
}
const onCancel = () => {
  emit('update:open', false)
}
watch(
  () => props.open,
  (val) => {
    if (val) {
      currentData.value = { ...props.rowData }
    }
  }
)
</script>
<style lang="less" scoped>
:deep(.ant-modal) {
  div[aria-hidden='true'] {
    display: none !important;
  }
}
.b1,
.b2,
.b3 {
  display: inline-block;
  background: #000;
  border-radius: 50%;
}
.circleWrap {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  margin-right: 20px;
  border-radius: 2px;
  cursor: pointer;
  &:hover {
    background-color: #00000020;
  }
}
.active {
  background-color: var(--secondary-color);
  border: 1px dashed var(--primary-color);
}
.b1 {
  width: 6px;
  height: 6px;
}
.b2 {
  width: 8px;
  height: 8px;
}
.b3 {
  width: 10px;
  height: 10px;
}
.disabled {
  color: #00000080;
  filter: opacity(0.6);
}
</style>
